/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.postbar.util;

import cn.ac.iie.di.postbar.entity.MongoDB;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.bson.Document;

/**
 *
 * @author Administrator
 */
public class SearchMongodb {

    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(SearchMongodb.class.getName());
    private MongoDB mongoDB;
    private HashMap valueMap = new HashMap();

    public SearchMongodb() {
    }

    public SearchMongodb(MongoDB mongoDB) {
        this.mongoDB = mongoDB;
    }

    private MongoClientOptions getConfOptions() {
        return MongoClientOptions.builder().socketKeepAlive(true)// 是否保持长连接
                .socketTimeout(1000000)//read数据超时时间
                .readPreference(ReadPreference.primary()) //最近优先策略
                .alwaysUseMBeans(true)//是否重发
                .connectionsPerHost(200)//每个地址最大请求输
                .maxWaitTime(1000 * 60 * 2)//长衔接最大请求数
                .threadsAllowedToBlockForConnectionMultiplier(100)//一个socket最大的等待请求数
                .writeConcern(WriteConcern.JOURNALED).build();
    }

    public MongoCollection<Document> getConnect() {
        MongoCollection<Document> mc = null;
        while (true) {
            try {
                String hostPort[] = mongoDB.getHost().split(":");
                List<ServerAddress> seeds = new ArrayList<>();//ip和端口号
                seeds.add(new ServerAddress(hostPort[0], Integer.parseInt(hostPort[1])));
                //用户名和库和密码
                MongoCredential credentials = MongoCredential.createScramSha1Credential(mongoDB.getUser(), mongoDB.getDb(), mongoDB.getPasswd().toCharArray());
                List<MongoCredential> credentialsList = new ArrayList<>();
                credentialsList.add(credentials);
                //        conn = new MongoClient(seeds, getConfOptions());
                MongoClient conn = new MongoClient(seeds, credentialsList, getConfOptions());
                MongoDatabase db = conn.getDatabase(mongoDB.getDb());
                mc = db.getCollection(mongoDB.getTable());
                logger.info(mongoDB.getDb() + " mongo connect is ok");
                break;
            } catch (Exception e) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }
        }
        return mc;
    }

    //name1条件查询字段
    //value条件查询字段值
    //name2需要查询的结果字段
    public String getValueByU_Name_Column(MongoCollection mongodbCollection, final String name1, String value, final String name2) {
        final HashMap<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(name2, "");
        try {
            FindIterable<Document> iterold = mongodbCollection.find(Filters.eq(name1, value));
            iterold.forEach(new Block<Document>() {
                @Override
                public void apply(Document _doc) {
                    if (_doc.isEmpty()) {
                        logger.info(name1 + " hasn't record!!!");
                        System.exit(0);
                    } else {
                        String value = (String) _doc.get(name2);
                        valueMap.put(name2, value);
                    }
                }
            }
            );
        } catch (Exception e) {
            logger.error("search mongoDB failed,cause " + e.getMessage(), e);
        }
        return valueMap.get(name2);
    }

    //跟帖表,主贴标题,用户昵称,吧名/板块名
    public HashMap<String, String> getValueByColumn(MongoCollection mongodbCollection, final String name1, String value, final String name2, final String name3) {
        final HashMap<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(name2, "");
        valueMap.put(name3, "");
        try {
            FindIterable<Document> iterold = mongodbCollection.find(Filters.eq(name1, value));
            iterold.forEach(new Block<Document>() {
                @Override
                public void apply(Document _doc) {
                    if (_doc.isEmpty()) {
                        logger.info(name1 + " hasn't record!!!");
                        System.exit(0);
                    } else {
                        String value2 = (String) _doc.get(name2);
                        valueMap.put(name2, value2);
                        String value3 = (String) _doc.get(name3);
                        valueMap.put(name3, value3);
                    }
                }
            }
            );
        } catch (Exception e) {
            logger.error("search mongoDB failed,cause " + e.getMessage(), e);
        }
        return valueMap;
    }
}
